<?php
/**
 * 默认系统级函数库文件
 */
class Core
{
	private static $convent	=	array();
	
	/**
	 * 程序运行入口
	 */
	static function run()
	{
		if(self::$convent['session'])
		{
			self::session();
		}
		
		$tmp	=	explode('.', strtolower($_REQUEST['a']));
		self::action($tmp[0], $tmp[1]);
	}
	
	/**
	 * 运行action前做一次过滤和其它设置 
	 */
	static function prepro()
	{
		self::$convent	=	array_merge(import('#/convent.php'), import(APP_PATH.'/convent.php'));

		ob_start(array('Core', 'outputFilter'));
		
		register_shutdown_function(array('Core', '_shutdownFunction'));
		set_error_handler(array('Core', '_errorHandler'), E_ALL);
		set_exception_handler(array('Core', '_exceptionHandler'));
		
		//push default "Content-type" and charset, you can rush with other below this
		header('Content-type: text/html; charset=utf-8');
		
		if(!empty($_REQUEST['R']))
		{
			$_GET	=	array();
			$tmp	=	explode('-', $_REQUEST['R']);
			$_REQUEST['a']	=	array_shift($tmp);
			if($tmp)
			{
				$c	=	count($tmp);
				if($c%2)
				{
					$c++;
					array_push($tmp, null);
				}
				for($i=0;$i<$c;$i+=2)
				{
					$_GET[$tmp[$i]]	=	$tmp[$i+1];
				}
				$_REQUEST	=	array_merge($_REQUEST, $_GET, $_POST);
			}
			unset($_REQUEST['R'], $tmp);
		}
		else
		{
			if(!isset($_REQUEST['a']))
			{
				$_REQUEST['a']	=	self::$convent['action'];
			}
		}
		if(false===strpos($_REQUEST['a'],'.'))
		{
			$_REQUEST['a']	.=	'.show';
		}
		$_REQUEST['a']	=	strtolower($_REQUEST['a']);
		
		define('TPL_PATH',	APP_PATH. self::$convent['tpl_path']);
		define('SRC_PATH',	APP_PATH. self::$convent['src_path']);
		define('DATA_PATH',	APP_PATH. self::$convent['data_path']);
		
		$root	=	MOD_WIN?str_replace('\\','/',dirname($_SERVER['SCRIPT_NAME'])):dirname($_SERVER['SCRIPT_NAME']);
		define('WEB_ROOT',	($root=='/'?'':$root));
		
		if(false!==strpos(self::$convent['tpl_path'],'../'))
		{
			$c	=	substr_count(self::$convent['tpl_path'], '../');
			strtok(strrev(WEB_ROOT), '/');
			while($c-- > 1){strtok('/');}
			
			define('WEB_THEME', (strrev(strtok('')). str_replace('../', '', self::$convent['tpl_path'])).'/'.View::theme());
		}
		else
		{
			define('WEB_THEME',	WEB_ROOT.self::$convent['tpl_path'].'/'.View::theme());
		}
	}
	
	/**
	 * 输出过滤
	 */
	static function outputFilter($string)
	{
		if(!$string) return '';
		
		if(self::$convent['rewrite_auto'] && false!==strpos($string,'./?a='))
		{
			$string	=	preg_replace_callback('~(href|src|action)=(["\'])(\./\?.*?)\2~i', array(__CLASS__,'_OF_CB'),$string);
		}
		
		if(!headers_sent())
		{
			if(self::$convent['compress'] && function_exists('ob_gzhandler'))
			{
				$string	=	ob_gzhandler($string, 1);
				/*
				else
				{
					$type	=	(false!==strpos($_SERVER["HTTP_ACCEPT_ENCODING"],'deflate')) ? 1 : (
								(false!==strpos($_SERVER['HTTP_ACCEPT_ENCODING'],'gzip')) ? 2 : 0 );
					if(!$type && isset($_SERVER['HTTP_TE']))
					{
						$type	=	(false!==strpos($_SERVER["HTTP_TE"],'deflate')) ? 1 : (
									(false!==strpos($_SERVER['HTTP_TE'],'gzip')) ? 2 : 0 );
					}
					if($type)
					{
						if(1===$type)
						{
							header("Content-Encoding: deflate");
							$string =       gzdeflate($string, self::$convent['compress']);
						}
						else
						{
							header("Content-Encoding: gzip");
							$string =       gzencode($string, self::$convent['compress']);
						}
						header("Vary: Accept-Encoding");
						header("Content-Length: ".strlen($string));
					}
				}
				*/
			}
		}
		
		return $string;
	}
	static function _OF_CB($ms)
	{
		static $ext; $ext ? null : $ext = self::$convent['urlmask'];
		return $ms[1].'='.$ms[2].WEB_ROOT.'/'.str_replace(array('./?a=','&','='), array('','-','-'), $ms[3]).'.'.$ext.$ms[2];
	}
	
	static function _shutdownFunction()
	{
		Db::close();
		
		//Lib::log(1000*(microtime(true)-$GLOBALS['BTIME']));
		Lib::flushLog();
	}
	static function _errorHandler()
	{
		$err	=	func_get_args();
		throw new ErrorException($err[1], $err[0], 0, $err[2], $err[3]);
	}
	static function _exceptionHandler($e)
	{
		$errmsg	=	strval($e);
		if(self::$convent['debug'])
		{
			Debug::pre($errmsg);
			die;
		}
		else
		{
			Lib::log($errmsg);
			Show::go500($e->getMessage());
		}
	}
	
	static function session()
	{
		if(self::$convent['session_name'])
		{
			session_name(self::$convent['session_name']);
		}
		if(!session_id())
		{
			session_set_cookie_params(
				self::$convent['session_cookie_lifetime'],
				self::$convent['session_cookie_path'] ? self::$convent['session_cookie_path'] : WEB_ROOT,
				self::$convent['session_cookie_domain']
				);
		}
		if(self::$convent['session_lifetime'])
		{
			ini_set('session.gc_maxlifetime', self::$convent['session_lifetime']);
		}
		
		session_start();
	}
	
	/**
	 * action选择器/依据提供给入口函数的参数，自动加载运行不同的action
	 */
	static function action($controller, $action, $dir=null)
	{
		try
		{
			null===$dir ? null : $dir.='/';
			import('$/controller/'.$dir.$controller.'.php');
		}
		catch(Exception $e)
		{
			Show::go400();
		}
		
		$controller	=	ucfirst($controller).'Controller';
		if(method_exists($controller, $action))
		{
			call_user_method($action, new $controller);
//			$obj	=	new $controller();
//			$obj->$action();
		}
		else
		{
			Show::go400();
		}
	}
	
	/**
	 * 取系统行为配置信息
	 */
	static function cfg($key)
	{
		return self::$convent[$key];
	}
	
	static function set400Handler($controller, $action)
	{
		Show::$hdl400	=	array($controller, $action);
	}
	static function set500Handler($controller, $action)
	{
		Show::$hdl500	=	array($controller, $action);
	}
	static function setNoticeHandler($controller, $action)
	{
		Show::$hdlnot	=	array($controller, $action);
	}
	static function setErrorHandler($controller, $action)
	{
		Show::$hdlerr	=	array($controller, $action);
	}
	
}

function __autoload($class)
{
	switch($class)
	{
	case 'Db':		import('#/db.php');		break;
	case 'Debug':	import('#/dbg.php');	break;
	case 'Show':	import('#/show.php');	break;
	case 'Html':	import('#/html.php');	break;
	default:
		if('Helper'===substr($class, -6))
		{
			if('A'===substr($class, -7, 1))
				import('#/helper/'.substr($class,0, -7).'.php');
			else 
				import('$/helper/'.substr($class, 0, -6).'.php');
		}
		else
		{
			import('$/model/'.$class.'.php');
		}
	}
}

?>